# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  https://gitee.com/autumner/pythoncookbook
@software: PyCharm 
@file: socke_pipe_client.py 
@time: 2019/7/23 上午11:01
@note:让socket的服务端和客户端各自独立运行

"""
from multiprocessing.connection import Client
from multiprocessing.reduction import recv_handle
from socket import socket, AF_INET, SOCK_STREAM
import os


def worker(server_address):
    serv = Client(server_address, authkey=b'peekaboo')
    serv.send(os.getpid())
    while True:
        fd = recv_handle(serv)
        print('WORKER: GOT FD', fd)
        with socket(AF_INET, SOCK_STREAM, fileno=fd) as client:
            while True:
                msg = client.recv(1024)
                if not msg:
                    break
                print('WORKER: RECV {!r}'.format(msg))
                client.send(msg)


if __name__ == '__main__':
    import sys
    if len(sys.argv) != 2:
        print(f"Usage:{sys.argv[0]} server_address", file=sys.stderr)
        raise SystemExit(1)

    worker(sys.argv[1])

"""
Example usage:
open Terminal:
python3 socket_pipe_client.py /tmp/servconn
"""